package com.pan.demo.utils;

import java.lang.reflect.Field;
import java.util.List;

public class SimpleJson {

    public <T> String mapper(T obj) throws IllegalAccessException {
        Class clazz =  obj.getClass();
        Field[] fields = clazz.getDeclaredFields();
        String json = "";
        for (int i = 0; i < fields.length; i++) {
            Field field = fields[i];
            field.setAccessible(true);
            String key = field.getName();
            String value = field.get(obj).toString();
            json += json.length()==0? "\""+key+"\": \""+value+"\"" :
                    ", \""+key+"\": \""+value+"\"";
        }
        json = "{"+json+"}";
        return json;
    }

    public <T> String mapperList(List<T> li){
        String result = li.stream().map(obj -> {
                    try {
                        return mapper(obj);
                    } catch (IllegalAccessException e) {
                        throw new RuntimeException(e);
                    }
                }).reduce((a,b)->a+","+b).get();
        return "["+result+"]";
    }

}
